package de.fmannan.addbook.views.actions;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

import de.fmannan.addbook.domainmodel.Contact;
import de.fmannan.addbook.domainmodel.Group;
import de.fmannan.addbook.editor.OpenEditorActionDelegate;

public class ContactNewAction implements IObjectActionDelegate {

	public ContactNewAction() {
		// TODO Auto-generated constructor stub
	}

	public static final String ID = "de.fmannan.addbook.views.actions.ContactNewAction";
	private static Logger log = Logger.getLogger(ContactNewAction.class);
	
	/**
	 * Memorized active part.
	 */
    private IWorkbenchPart activePart;

    /**
     * Memorized active selection.
     */
    private ISelection activeSelection;

    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        activePart = targetPart;
    }

    /**
	 * Is executed when the user chooses the option to delete a contact via the
	 * contacts popup menu.
	 */
    public void run(IAction action) {
        
        if ( activeSelection instanceof IStructuredSelection) {
            IStructuredSelection structuredSelection = (IStructuredSelection) activeSelection;
            Object firstSelected = structuredSelection.getFirstElement();
            
            // the item that the user clicked on must be a group in order to
			// create a new contact as the groups child
            if ( firstSelected instanceof Group ) {
				Group elem = (Group)firstSelected;
				Contact obj = new Contact("", "");
				obj.setParent(elem);
				// A new editor windows should be opened in order to create a
				// new Contact
				OpenEditorActionDelegate.openEditor(PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage(), obj);	            }
        }        
    }
    
    
    public void selectionChanged(IAction action, ISelection selection) {
        activeSelection = selection;
    }
}
